#!/bin/zsh
set -euo pipefail

SCRIPT_DIR="${0:A:h}"
STATE_DIR="$HOME/Library/Application Support/r5d"
LOG_DIR="$HOME/Library/Logs/r5d"
LOG_FILE="$LOG_DIR/bootstrap.log"
WORKER_LABEL="macos-vm"
VM_NAME="r5d-macos"

mkdir -p "$STATE_DIR" "$LOG_DIR"
chmod 700 "$STATE_DIR" "$LOG_DIR"
exec > >(tee -a "$LOG_FILE") 2>&1

if [[ -f "$SCRIPT_DIR/.r5d-worker-label" ]]; then
  configured_label="$(tr -d '[:space:]' < "$SCRIPT_DIR/.r5d-worker-label")"
  if [[ "$configured_label" =~ '^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$' ]]; then
    WORKER_LABEL="$configured_label"
  fi
fi
if [[ -f "$SCRIPT_DIR/.r5d-vm-name" ]]; then
  configured_name="$(tr -d '[:space:]' < "$SCRIPT_DIR/.r5d-vm-name")"
  if [[ "$configured_name" =~ '^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$' ]]; then
    VM_NAME="$configured_name"
  fi
fi

print
print "r5d macOS VM setup"
print "Worker label: $WORKER_LABEL"
print

if [[ "$(uname -s)" != "Darwin" || "$(uname -m)" != "arm64" ]]; then
  print -u2 "This installer requires macOS on Apple silicon (arm64)."
  exit 1
fi

print "Checking outbound network access…"
if ! /usr/bin/curl --fail --silent --show-error --location --head --max-time 20 https://r5d.dev/ >/dev/null; then
  print -u2 "Could not reach r5d.dev. Check this VM's network connection, then run the installer again."
  exit 1
fi

if ! xcode-select -p >/dev/null 2>&1; then
  print "Apple Command Line Tools are required. macOS will open its installer."
  print "Complete that installer, then run this command again."
  xcode-select --install >/dev/null 2>&1 || true
  read -r "?Press Return after the Command Line Tools installation finishes, or close this window and retry later: "
  if ! xcode-select -p >/dev/null 2>&1; then
    print "Command Line Tools are not installed yet. Run this setup again after installation completes."
    exit 1
  fi
fi

if [[ ! -x /opt/homebrew/bin/brew ]]; then
  print "Installing Homebrew. macOS may ask for the local account password."
  /bin/bash -c "$(/usr/bin/curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

eval "$(/opt/homebrew/bin/brew shellenv)"
brew update
brew install gh node bun

print "Installing r5d command-line tools."
npm install --global --omit=dev @ricsam/r5dctl @ricsam/r5d-worker @ricsam/r5d-browser

gh --version >/dev/null
node --version >/dev/null
bun --version >/dev/null
r5dctl --version >/dev/null
r5d-worker --version >/dev/null
r5d-browser --version >/dev/null

print
"$SCRIPT_DIR/install-worker-launch-agent.sh" "$WORKER_LABEL" "$VM_NAME"

touch "$STATE_DIR/bootstrap-complete"
chmod 600 "$STATE_DIR/bootstrap-complete"
print
print "Tools installed. The visible r5d worker Terminal is opening for configured executor startup…"
print "You may close this setup window."
